package com.wetao.lib_common.video;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ToastUtil;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

/**
 * author: zhouyh
 * description:音频播放器
 */
public class AudioPlayerManager {

    private static final String TAG = "AudioPlayerManager";
    public static final String STR_DURATION = "duration";
    public static final String STR_CURRENT_POSITION = "currentPosition";
    private static AudioPlayerManager instance;
    private Context context;
    private SimpleExoPlayer mediaPlayer;
    private DataSource.Factory dataSourceFactory;

    private Timer timer;
    private TimerTask task;
    private CallbackPlay callbackPlay;

    private AudioPlayerManager(Context context) {
        this.context = context;
        createPlayer();
    }

    public static AudioPlayerManager getInstance(Context context) {
        synchronized (AudioPlayerManager.class) {
            if (instance == null) {
                instance = new AudioPlayerManager(context);
            }
        }
        return instance;
    }

    public ExoPlayer getMediaPlayer() {
        return mediaPlayer;
    }


    //设置播放url
    public void setAudioUrl(String audioUrl) {
        if (timer != null) {
            timer.cancel();
        }
        try {
            //这是一个代表将要被播放的媒体的MediaSource
            MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(Uri.parse(audioUrl));
            mediaPlayer.prepare(mediaSource);
            mediaPlayer.setPlayWhenReady(false);
            if (isPlaying()) {
                mediaPlayer.stop(true);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置播放file
    public void setAudioFile(File file) {

        if (timer != null) {
            timer.cancel();
        }
        try {
            //这是一个代表将要被播放的媒体的MediaSource
            MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(Uri.fromFile(file));
            mediaPlayer.prepare(mediaSource);
            mediaPlayer.setPlayWhenReady(false);
            if (isPlaying()) {
                mediaPlayer.stop(true);
            }
        } catch (Exception e) {
            ToastUtil.initToast("异常" + e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 切换音频
     */
    public void changeAudioUrl(String url) {
        if (url.startsWith("https://")||url.startsWith("http://")) {
            setAudioUrl(url);
        } else {
            setAudioFile(new File(url));
        }
        mediaPlayer.setPlayWhenReady(true);
    }

    //开始播放
    public void start() {
        mediaPlayer.setPlayWhenReady(true);
    }

    //判断是否是播放状态
    public boolean isPlaying() {
        int playbackState = mediaPlayer.getPlaybackState();
        if (playbackState == SimpleExoPlayer.STATE_READY && mediaPlayer.getPlayWhenReady()) {
            return true;
        }
        return false;
    }

    //播放，带回调事件
    public void playWithCompletionListener(String url, Player.EventListener listener) {
        if (listener != null) {
            mediaPlayer.addListener(listener);
        }
        if (url == null) return;
        if (url.startsWith("https://")||url.startsWith("http://")) {
            setAudioUrl(url);
        } else {
            setAudioFile(new File(url));
        }
        mediaPlayer.setPlayWhenReady(true);
    }


    //播放or暂停
    public void playOrPause() {
        if (isPlaying()) {
            timer.cancel();
            mediaPlayer.setPlayWhenReady(false);
        } else {
            mediaPlayer.setPlayWhenReady(true);
        }
    }

    //切换播放速率
    public void switchSpeed(float speed) {
        // API 23 （6.0）以上 ，通过设置Speed改变音乐的播放速率
        if (isPlaying()) {
            // 判断是否正在播放，未播放时，要在设置Speed后，暂停音乐播放
            getMediaPlayer().setPlaybackParameters(new PlaybackParameters(speed));
        } else {
            getMediaPlayer().setPlaybackParameters(new PlaybackParameters(speed));
            getMediaPlayer().setPlayWhenReady(false);
        }
    }

    //停止播放
    public void stop(boolean reset) {
        if (mediaPlayer != null) {
            mediaPlayer.stop(reset);
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    //释放资源
    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }

        instance = null;
    }

    //创建一个新的player
    private void createPlayer() {
        // 创建带宽
        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        // 创建轨道选择工厂
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        // 创建轨道选择器实例
        TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
        //step2.创建播放器
        mediaPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
        //创建一个DataSource对象，通过它来下载多媒体数据
        dataSourceFactory = new DefaultDataSourceFactory(context,
                Util.getUserAgent(context, "loader"));
    }

    public void updateSeekBar() {
        // 使用Timer 定时器去获取当前进度
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                LogUtils.i("refreshPosition start");
                refreshPosition(false);
            }
        };
        // 100ms后每间隔1s、执行一次run方法
        timer.schedule(task, 100, 1000);
    }


    public void reset(int position) {
        if (mediaPlayer == null) {
            return;
        }
        if (timer != null) {
            timer.cancel();
        }
        mediaPlayer.setPlayWhenReady(false);
        mediaPlayer.seekTo(position);
        //只有在播放状态才会拖动后重新播放
    }

    public void refreshPosition(boolean isCompletion) {
        if (mediaPlayer == null) {
            return;
        }
        // 一秒钟获取一次当前进度
        long currentPosition = 0;
        if (!isCompletion && isPlaying()) {
            currentPosition = mediaPlayer.getCurrentPosition();
        }
        // 获取当前歌曲总长度
        long duration = mediaPlayer.getDuration();
        // 拿到我们在MainActivity创建的handler发消息，消息可以携带数据

        //obj只能携带一个数据
        Bundle bundle = new Bundle(); // map
        bundle.putLong(STR_DURATION, duration);
        bundle.putLong(STR_CURRENT_POSITION, currentPosition);
        if (callbackPlay != null) {
            callbackPlay.onCurrentPosition(bundle);
        }
    }


    public void setCallbackPlay(CallbackPlay callbackPlay) {
        this.callbackPlay = callbackPlay;
    }

    public interface CallbackPlay {
        void onCurrentPosition(Bundle bundle);
    }


}
